<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>积分规则管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .modal-backdrop {
            z-index: 1040 !important;
        }
        .modal-content {
            z-index: 1050 !important;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="mb-0">积分规则管理</h2>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRuleModal">
                <i class="fa fa-plus me-2"></i>添加规则
            </button>
        </div>

        <!-- 积分规则表格 -->
        <div class="card">
            <div class="card-body">
                <table class="table table-bordered align-middle mb-0" id="rulesTable">
                    <thead class="table-light">
                    <tr>
                        <th style="width:60px;">#</th>
                        <th>规则名称</th>
                        <th>积分值</th>
                        <th style="width:100px;">是否启用</th>
                        <th>创建时间</th>
                        
                        <th style="width:160px;">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <!-- JS填充 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 添加积分规则模态框 -->
        <div class="modal fade" id="addRuleModal" tabindex="-1" aria-labelledby="addRuleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addRuleModalLabel">添加积分规则</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="ruleNameInput" class="form-label">规则名称</label>
                            <input type="text" class="form-control" id="ruleNameInput" placeholder="请输入规则名称">
                        </div>
                         <div class="mb-3">
                            <label for="rulePointsInput" class="form-label">积分值</label>
                            <input type="number" class="form-control" id="rulePointsInput" placeholder="请输入积分值">
                        </div>
                        <div class="mb-3">
                            <label for="ruleTypeInput" class="form-label">规则类型</label>
                            <input type="text" class="form-control" id="ruleTypeInput" placeholder="请输入规则类型 (例如: ARTICLE_CREATE)">
                        </div>
                        <div class="mb-3">
                             <label for="isActiveInput" class="form-label">是否启用</label>
                             <select class="form-select" id="isActiveInput">
                                 <option value="true">启用</option>
                                 <option value="false">禁用</option>
                             </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="addRuleBtn">添加</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑积分规则模态框 -->
        <div class="modal fade" id="editRuleModal" tabindex="-1" aria-labelledby="editRuleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editRuleModalLabel">编辑积分规则</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="editRuleNameInput" class="form-label">规则名称</label>
                            <input type="text" class="form-control" id="editRuleNameInput" placeholder="请输入规则名称">
                        </div>
                         <div class="mb-3">
                            <label for="editRulePointsInput" class="form-label">积分值</label>
                            <input type="number" class="form-control" id="editRulePointsInput" placeholder="请输入积分值">
                        </div>
                         <div class="mb-3">
                             <label for="editRuleTypeInput" class="form-label">规则类型</label>
                             <input type="text" class="form-control" id="editRuleTypeInput" placeholder="请输入规则类型">
                         </div>
                         <div class="mb-3">
                              <label for="editIsActiveInput" class="form-label">是否启用</label>
                              <select class="form-select" id="editIsActiveInput">
                                  <option value="true">启用</option>
                                  <option value="false">禁用</option>
                              </select>
                         </div>
                         <!-- 隐藏字段用于存储规则ID -->
                         <input type="hidden" id="editRuleId">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveEditRuleBtn">保存</button>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/jquery-3.7.1.min.js"></script>
    <script>
        // 积分规则数据
        let pointRules = [];
        let editRuleId = null; // 用于存储当前编辑的规则ID

        // 渲染表格
        function renderTable() {
            const tbody = document.querySelector('#rulesTable tbody');
            tbody.innerHTML = '';
            pointRules.forEach((rule, idx) => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${rule.id || idx + 1}</td>
                    <td>${rule.ruleName || ''}</td>
                    <td>${rule.pointValue || 0}</td>
                    <td>
                        ${rule.isActive ? 
                            '<button class="btn btn-sm btn-success disabled">启用</button>' :
                            '<button class="btn btn-sm btn-secondary disabled">禁用</button>'}
                    </td>
                    <td>${rule.createdAt || ''}</td>
                    
                    <td>
                        <!-- TODO: 添加编辑和删除按钮 -->
                        <button class="btn btn-sm btn-warning me-2 edit-btn" data-id="${rule.id}"><i class="fa fa-pencil"></i> 编辑</button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${rule.id}"><i class="fa fa-trash"></i> 删除</button>
                    </td>`;
                 // TODO: 绑定编辑和删除事件
                // 绑定删除事件
                $(tr).find('.delete-btn').click(function () {
                    const ruleId = $(this).data('id');
                    if (confirm('确定要删除该积分规则吗？')) {
                        $.ajax({
                            url: 'http://localhost:8082/api/point-rules/' + ruleId,
                            method: 'DELETE',
                            dataType: 'json',
                            success: function(data) {
                                if (data.code === 200) {
                                    fetchRules(); // 刷新列表
                                    alert('删除成功！');
                                } else {
                                    console.error('删除失败:', data.msg);
                                    alert('删除失败：' + (data.msg || '未知错误'));
                                }
                            },
                            error: function(xhr, status, error) {
                                 console.error('删除请求失败:', status, error, xhr.responseText);
                                alert('删除失败，无法连接到服务器');
                            }
                        });
                    }
                });
                // TODO: 绑定编辑事件
                $(tr).find('.edit-btn').click(function () {
                    const ruleId = $(this).data('id');
                    const ruleToEdit = pointRules.find(rule => rule.id === ruleId);
                    if (ruleToEdit) {
                        editRuleId = ruleId; // 存储当前编辑的规则ID
                        // 填充编辑模态框
                        $('#editRuleNameInput').val(ruleToEdit.ruleName);
                        $('#editRulePointsInput').val(ruleToEdit.pointValue);
                        $('#editRuleTypeInput').val(ruleToEdit.ruleType);
                        $('#editIsActiveInput').val(ruleToEdit.isActive ? 'true' : 'false'); // 设置下拉框的值
                        
                        const modal = new bootstrap.Modal(document.getElementById('editRuleModal'));
                        modal.show();
                    }
                });
                tbody.appendChild(tr);
            });
        }

        // 获取积分规则数据
        function fetchRules() {
            $.ajax({
                url: 'http://localhost:8082/api/point-rules', // 你的后端获取规则接口
                method: 'GET',
                dataType: 'json',
                success: function(data) {
                    if (data.code === 200 && Array.isArray(data.data)) {
                        pointRules = data.data;
                        renderTable();
                    } else {
                        console.error('获取积分规则数据失败:', data.msg);
                        alert('获取积分规则数据失败: ' + (data.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                     console.error('获取积分规则数据失败:', status, error, xhr.responseText);
                    alert('无法连接到积分规则接口');
                }
            });
        }

        // 添加积分规则
        document.getElementById('addRuleBtn').onclick = function () {
            const nameInput = document.getElementById('ruleNameInput');
             const pointsInput = document.getElementById('rulePointsInput');
            const name = nameInput.value.trim();
             const points = parseInt(pointsInput.value.trim(), 10);

            const typeInput = document.getElementById('ruleTypeInput');
            const isActiveSelect = document.getElementById('isActiveInput');
            const ruleType = typeInput.value.trim();
            const isActive = isActiveSelect.value === 'true';

            if (!name) {
                nameInput.classList.add('is-invalid');
                nameInput.focus();
                return;
            }
             if (isNaN(points) || points < 0) {
                 pointsInput.classList.add('is-invalid');
                 pointsInput.focus();
                 alert('请输入有效的积分值');
                 return;
             }

            nameInput.classList.remove('is-invalid');
             pointsInput.classList.remove('is-invalid');
             typeInput.classList.remove('is-invalid');

            const btn = this;
            btn.disabled = true;
            btn.textContent = '添加中...';

            const ruleData = {
                ruleName: name,
                pointValue: points,
                ruleType: ruleType,
                isActive: isActive
            };

            $.ajax({
                url: 'http://localhost:8082/api/point-rules/add', // 你的后端添加规则接口
                method: 'POST', // 通常添加是 POST 请求
                contentType: 'application/json', // 声明请求体为 JSON 格式
                data: JSON.stringify(ruleData), // 发送 JSON 数据
                dataType: 'json', // 期望后端返回的数据格式
                success: function(data) {
                    if (data.code === 200) {
                        fetchRules(); // 刷新列表
                        nameInput.value = ''; // 清空输入框
                         pointsInput.value = '';
                        const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('addRuleModal'));
                        modal.hide(); // 关闭模态框
                        alert('添加成功！');
                    } else {
                         console.error('添加失败:', data.msg);
                        alert('添加失败：' + (data.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                     console.error('添加请求失败:', status, error, xhr.responseText);
                    alert('添加失败，无法连接到服务器');
                },
                complete: function() {
                    btn.disabled = false;
                    btn.textContent = '添加';
                }
            });
        };

        // 编辑保存按钮点击事件
        $('#saveEditRuleBtn').click(function () {
            const nameInput = $('#editRuleNameInput');
            const pointsInput = $('#editRulePointsInput');
            const typeInput = $('#editRuleTypeInput');
            const isActiveSelect = $('#editIsActiveInput');

            const name = nameInput.val().trim();
            const points = parseInt(pointsInput.val().trim(), 10);
            const ruleType = typeInput.val().trim();
            const isActive = isActiveSelect.val() === 'true';

            if (!name) {
                nameInput.addClass('is-invalid');
                nameInput.focus();
                return;
            }
            if (isNaN(points) || points < 0) {
                pointsInput.addClass('is-invalid');
                pointsInput.focus();
                alert('请输入有效的积分值');
                return;
            }
             if (!ruleType) { // 简单的规则类型验证
                 typeInput.addClass('is-invalid');
                 typeInput.focus();
                 alert('请输入规则类型');
                 return;
             }

            nameInput.removeClass('is-invalid');
            pointsInput.removeClass('is-invalid');
             typeInput.removeClass('is-invalid');

            if (editRuleId !== null) {
                const ruleData = {
                    id: editRuleId, // 包含ID
                    ruleName: name,
                    pointValue: points,
                    ruleType: ruleType,
                    isActive: isActive
                    // 注意：这里只包含了可编辑的字段，其他字段如 createdAt, updatedAt 等通常由后端处理
                };

                $.ajax({
                    url: 'http://localhost:8082/api/point-rules/' + editRuleId, // 你的后端更新规则接口
                    method: 'PUT', // 使用 PUT 方法
                    contentType: 'application/json',
                    data: JSON.stringify(ruleData),
                    dataType: 'json',
                    success: function(data) {
                        if (data.code === 200) {
                            alert('编辑成功！');
                            const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editRuleModal'));
                            modal.hide(); // 关闭模态框
                            fetchRules(); // 刷新列表
                        } else {
                            console.error('编辑失败:', data.msg);
                            alert('编辑失败：' + (data.msg || '未知错误'));
                        }
                    },
                    error: function(xhr, status, error) {
                         console.error('编辑请求失败:', status, error, xhr.responseText);
                        alert('编辑失败，无法连接到服务器');
                    }
                });
            } else {
                 console.error('编辑错误: 未找到规则ID');
                 alert('编辑失败，未找到规则ID');
            }
        });

        // 清除输入框校验
         document.getElementById('ruleNameInput').oninput = function () {
             this.classList.remove('is-invalid');
         };
          document.getElementById('rulePointsInput').oninput = function () {
              this.classList.remove('is-invalid');
          };
          document.getElementById('ruleTypeInput').oninput = function () { // 添加规则类型输入框的校验清除
              this.classList.remove('is-invalid');
          };
          // 添加编辑输入框的清除校验
           $('#editRuleNameInput').on('input', function() {
               $(this).removeClass('is-invalid');
           });
           $('#editRulePointsInput').on('input', function() {
               $(this).removeClass('is-invalid');
           });
           $('#editRuleTypeInput').on('input', function() {
               $(this).removeClass('is-invalid');
           });

        // 初始化表格（页面加载时拉取数据）
        fetchRules();
    </script>
</body>
</html> 